<template>
  <div class="page-container">
    <div>
      <el-card>
        <template slot="header">
          <div class="card-header">
            <span class="card-title">算力主机管理</span>
          </div>
        </template>
        <!-- 搜索和操作栏 -->
        <el-row :gutter="20" class="search-bar">
          <el-col :span="6">
            <el-input v-model="searchQuery" placeholder="搜索主机名称或IP" clearable>
              <template slot="append">
                <el-button icon="el-icon-search"></el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
              添加主机
            </el-button>
            <el-button icon="el-icon-refresh" @click="fetchHosts">
              刷新
            </el-button>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-select v-model="statusFilter" placeholder="状态筛选" clearable>
              <el-option label="在线" value="active"></el-option>
              <el-option label="离线" value="inactive"></el-option>
              <el-option label="错误" value="error"></el-option>
            </el-select>
          </el-col>
        </el-row>

        <!-- 主机列表表格 -->
        <el-table 
          :data="filteredHosts" 
          stripe 
          class="table-container"
          v-loading="loading"
        >
          <el-table-column prop="name" label="主机名称" width="240" />
          <el-table-column prop="ip" label="节点IP" width="200" />
          <el-table-column prop="status" label="状态" width="120">
            <template slot-scope="scope">
              <span :class="`status-${scope.row.status}`">
                {{ statusText[scope.row.status] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="cpuUsage" label="CPU使用率" width="180">
            <template slot-scope="scope">
              <el-progress
                :percentage="scope.row.cpuUsage"
                :color="scope.row.cpuUsage > 80 ? '#f56c6c' : (scope.row.cpuUsage > 60 ? '#e6a23c' : '#67c23a')"
                :show-text="false"
                v-if="scope.row.status === 'active'"
              />
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="gpuUsage" label="AI加速卡使用率" width="180">
            <template slot-scope="scope">
              <el-progress
                :percentage="scope.row.gpuUsage"
                :color="scope.row.gpuUsage > 80 ? '#f56c6c' : (scope.row.gpuUsage > 60 ? '#e6a23c' : '#67c23a')"
                :show-text="false"
                v-if="scope.row.status === 'active' && scope.row.hasGpu"
              />
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="memory" label="内存使用" width="180">
            <template slot-scope="scope">
              <span v-if="scope.row.status === 'active'">
                {{ scope.row.memoryUsed }}GB / {{ scope.row.memoryTotal }}GB
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button size="small" @click="handleView(scope.row)">
                查看
              </el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <el-pagination
          style="margin-top: 20px; justify-content: flex-end;"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalHosts"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="currentPage = $event"
          @size-change="pageSize = $event"
        ></el-pagination>
      </el-card>
    </div>

  <!-- 主机详情对话框 -->
  <el-dialog 
    :title="dialogTitle" 
    :visible.sync="detailDialogVisible" 
    width="60%"
  >
    <div v-if="currentHost">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="主机名称">{{ currentHost.name }}</el-descriptions-item>
        <el-descriptions-item label="节点IP">{{ currentHost.ip }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <span :class="`status-${currentHost.status}`">
            {{ statusText[currentHost.status] }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentHost.createTime }}</el-descriptions-item>
        <el-descriptions-item label="CPU架构">{{ currentHost.cpuArch }}</el-descriptions-item>
        <el-descriptions-item label="操作系统">{{ currentHost.osVersion }}</el-descriptions-item>
      </el-descriptions>

      <h3 style="margin-top: 20px;">运行情况</h3>
      
      <el-row :gutter="20" style="margin-top: 15px;">
        <el-col :span="12">
          <el-card class="metrics-card">
            <template slot="header">
              <span>CPU使用情况</span>
            </template>
            <div v-if="currentHost.status === 'active'">
              <div class="metrics-value">{{ currentHost.cpuUsage }}%</div>
              <div class="progress-container">
                <el-progress 
                  :percentage="currentHost.cpuUsage" 
                  :color="currentHost.cpuUsage > 80 ? '#f56c6c' : (currentHost.cpuUsage > 60 ? '#e6a23c' : '#67c23a')"
                ></el-progress>
              </div>
            </div>
            <div v-else>主机离线，无法获取数据</div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="metrics-card">
            <template slot="header">
              <span>AI加速卡使用情况</span>
            </template>
            <div v-if="currentHost.status === 'active' && currentHost.hasGpu">
              <div class="metrics-value">{{ currentHost.gpuUsage }}%</div>
              <div class="progress-container">
                <el-progress 
                  :percentage="currentHost.gpuUsage" 
                  :color="currentHost.gpuUsage > 80 ? '#f56c6c' : (currentHost.gpuUsage > 60 ? '#e6a23c' : '#67c23a')"
                ></el-progress>
              </div>
            </div>
            <div v-else-if="!currentHost.hasGpu">该主机无AI加速卡</div>
            <div v-else>主机离线，无法获取数据</div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 15px;">
        <el-col :span="12">
          <el-card class="metrics-card">
            <template slot="header">
              <span>内存使用情况</span>
            </template>
            <div v-if="currentHost.status === 'active'">
              <div class="metrics-value">{{ currentHost.memoryUsed }}GB / {{ currentHost.memoryTotal }}GB</div>
              <div class="progress-container">
                <el-progress 
                  :percentage="Math.round((currentHost.memoryUsed / currentHost.memoryTotal) * 100)" 
                  :color="(currentHost.memoryUsed / currentHost.memoryTotal) > 0.8 ? '#f56c6c' : ((currentHost.memoryUsed / currentHost.memoryTotal) > 0.6 ? '#e6a23c' : '#67c23a')"
                ></el-progress>
              </div>
            </div>
            <div v-else>主机离线，无法获取数据</div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="metrics-card">
            <template slot="header">
              <span>存储使用情况</span>
            </template>
            <div v-if="currentHost.status === 'active'">
              <div class="metrics-value">{{ currentHost.diskUsed }}GB / {{ currentHost.diskTotal }}GB</div>
              <div class="progress-container">
                <el-progress 
                  :percentage="Math.round((currentHost.diskUsed / currentHost.diskTotal) * 100)" 
                  :color="(currentHost.diskUsed / currentHost.diskTotal) > 0.8 ? '#f56c6c' : ((currentHost.diskUsed / currentHost.diskTotal) > 0.6 ? '#e6a23c' : '#67c23a')"
                ></el-progress>
              </div>
            </div>
            <div v-else>主机离线，无法获取数据</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div v-else style="text-align: center; padding: 40px;">
      <el-empty description="未选择主机"></el-empty>
    </div>

    <template slot="footer">
      <el-button @click="detailDialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="handleEdit(currentHost)" :disabled="!currentHost">编辑</el-button>
    </template>
  </el-dialog>

  <!-- 添加/编辑主机对话框 -->
  <el-dialog 
    :title="isEditing ? '编辑主机' : '添加主机'" 
    :visible.sync="editDialogVisible"
    width="500px"
  >
    <el-form :model="editForm" label-width="100px">
      <el-form-item label="主机名称">
        <el-input v-model="editForm.name"></el-input>
      </el-form-item>
      <el-form-item label="节点IP">
        <el-input v-model="editForm.ip"></el-input>
      </el-form-item>
      <el-form-item label="CPU架构">
        <el-select v-model="editForm.cpuArch" placeholder="请选择">
          <el-option label="x86_64" value="x86_64"></el-option>
          <el-option label="ARM64" value="ARM64"></el-option>
          <el-option label="LoongArch" value="LoongArch"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作系统">
        <el-input v-model="editForm.osVersion"></el-input>
      </el-form-item>
      <el-form-item label="是否有AI加速卡">
        <el-switch v-model="editForm.hasGpu"></el-switch>
      </el-form-item>
    </el-form>
    
    <template slot="footer">
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveHost">保存</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { listHosts, addHost, updateHost, delHost } from '@/api/resource_manage/host';

export default {
  name: 'HostManagement',
  data() {
    return {
      // 状态文本映射
      statusText: {
        active: '在线',
        inactive: '离线',
        error: '错误'
      },
      
      // 搜索和筛选相关
      searchQuery: '',
      statusFilter: '',
      currentPage: 1,
      pageSize: 10,
      loading: true,
      
      // 主机数据
      hosts: [],
      
      // 对话框控制
      detailDialogVisible: false,
      editDialogVisible: false,
      isEditing: false,
      
      // 当前选中的主机
      currentHost: null,
      
      // 编辑表单
      editForm: {
        id: null,
        name: '',
        ip: '',
        cpuArch: 'x86_64',
        osVersion: 'CentOS 7.9',
        hasGpu: true
      }
    };
  },
  computed: {
    // 总主机数
    totalHosts() {
      return this.hosts.length;
    },
    
    // 对话框标题
    dialogTitle() {
      return this.currentHost ? `${this.currentHost.name} 的详细信息` : '主机详情';
    },
    
    // 过滤后的主机列表
    filteredHosts() {
      let result = this.hosts;
      
      // 应用搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        result = result.filter(host => 
          host.name.toLowerCase().includes(query) || 
          host.ip.toLowerCase().includes(query)
        );
      }
      
      // 应用状态过滤
      if (this.statusFilter) {
        result = result.filter(host => host.status === this.statusFilter);
      }
      
      // 应用分页
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return result.slice(start, end);
    }
  },
  methods: {
    // 获取主机数据
    fetchHosts() {
      this.loading = true;
      listHosts()
        .then(response => {
          this.hosts = response.data || [];
          this.loading = false;
        })
        .catch(error => {
          console.error('获取主机列表失败:', error);
          // 使用模拟数据避免页面空白
          this.hosts = [
            {
              id: 1,
              name: '测试主机1',
              ip: '192.168.1.100',
              status: 'active',
              cpuUsage: 30,
              gpuUsage: 45,
              hasGpu: true,
              memoryUsed: 8,
              memoryTotal: 16,
              diskUsed: 50,
              diskTotal: 200,
              cpuArch: 'x86_64',
              osVersion: 'CentOS 7.9',
              createTime: '2024-01-01 10:00:00'
            },
            {
              id: 2,
              name: '测试主机2',
              ip: '192.168.1.101',
              status: 'inactive',
              cpuUsage: 0,
              gpuUsage: 0,
              hasGpu: false,
              memoryUsed: 0,
              memoryTotal: 32,
              diskUsed: 0,
              diskTotal: 500,
              cpuArch: 'ARM64',
              osVersion: 'Ubuntu 20.04',
              createTime: '2024-01-02 14:30:00'
            }
          ];
          this.loading = false;
          this.$message.warning('使用模拟数据，API连接失败');
        });
    },

    // 查看主机详情
    handleView(host) {
      this.currentHost = host;
      this.detailDialogVisible = true;
    },

    // 添加主机
    handleAdd() {
      this.isEditing = false;
      this.editForm = {
        id: null,
        name: '',
        ip: '',
        cpuArch: 'x86_64',
        osVersion: 'CentOS 7.9',
        hasGpu: true
      };
      this.editDialogVisible = true;
    },

    // 编辑主机
    handleEdit(host) {
      this.isEditing = true;
      this.currentHost = host;
      // 填充表单数据
      this.editForm = { ...host };
      this.detailDialogVisible = false;
      this.editDialogVisible = true;
    },

    // 删除主机
    handleDelete(host) {
      this.$confirm(
        `确定要删除主机 "${host.name}" (${host.ip}) 吗？此操作不可恢复。`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        delHost(host.id)
          .then(() => {
            this.$message.success('删除成功');
            this.fetchHosts(); // 重新获取数据以刷新列表
          })
          .catch(error => {
            console.error('删除主机失败:', error);
            this.$message.error('删除主机失败');
          });
      }).catch(() => {
        // 取消删除
      });
    },

    // 保存主机信息
    saveHost() {
      if (this.isEditing) {
        // 更新现有主机
        updateHost(this.editForm)
          .then(() => {
            this.$message.success('更新成功');
            this.editDialogVisible = false;
            this.fetchHosts(); // 重新获取数据以刷新列表
          })
          .catch(error => {
            console.error('更新主机失败:', error);
            this.$message.error('更新主机失败');
          });
      } else {
        // 添加新主机
        addHost(this.editForm)
          .then(() => {
            this.$message.success('添加成功');
            this.editDialogVisible = false;
            this.fetchHosts(); // 重新获取数据以刷新列表
          })
          .catch(error => {
            console.error('添加主机失败:', error);
            this.$message.error('添加主机失败');
          });
      }
    }
  },
  mounted() {
    this.fetchHosts();
  }
};
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  padding: 25px;
  min-height: 100%;
}
.page-container .card-title {
  font-size: 18px;
  font-weight: 500;
}


.monitor-header {
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.table-container {
  margin-top: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.status-active {
  color: #67C23A;
}
.status-inactive {
  color: #909399;
}
.status-error {
  color: #F56C6C;
}
.metrics-card {
  margin-bottom: 15px;
}
.metrics-value {
  font-size: 16px;
  font-weight: bold;
}
.progress-container {
  margin-top: 8px;
}
</style>
